package com.fary;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ctrip.framework.apollo.Config;
import com.ctrip.framework.apollo.spring.annotation.ApolloConfig;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Component;
import springfox.documentation.swagger.web.SwaggerResource;
import springfox.documentation.swagger.web.SwaggerResourcesProvider;

import java.util.ArrayList;
import java.util.List;

// 添加文档来源
@Component
@Primary
public class DocumentationConfig implements SwaggerResourcesProvider {
    // 获取ApolloConfig
    @ApolloConfig
    private Config appConfig;

    // 访问swagger-ui页面的时候都会执行get方法
    @Override
    public List<SwaggerResource> get() {
        List resources = new ArrayList<>();
        String swaggerDocJson = swaggerDocument();
        JSONArray jsonArray = JSONArray.parseArray(swaggerDocJson);
        for (Object object : jsonArray) {
            JSONObject jsonObject = (JSONObject) object;
            String name = jsonObject.getString("name");
            String location = jsonObject.getString("location");
            String version = jsonObject.getString("version");
            // 网关使用服务别名获取远程服务的SwaggerApi
            resources.add(swaggerResource(name, location, version));
        }
        return resources;
    }

    private String swaggerDocument() {
        String property = appConfig.getProperty("fary.swaggerDocument", "");
        return property;
    }

    private SwaggerResource swaggerResource(String name, String location, String version) {
        SwaggerResource swaggerResource = new SwaggerResource();
        swaggerResource.setName(name);
        swaggerResource.setLocation(location);
        swaggerResource.setSwaggerVersion(version);
        return swaggerResource;
    }
}